// 1.创建组件并配置路由;
// 2.布局，写页面；
// 3.查看接口文档，配置ajax,封装功能；
// 4.调接口，显示数据。
import Vue from 'vue';
import VueRouter from 'vue-router';
import { getUser } from '../utils/storage';
// import Login from '../views/login/index.vue';
// import Layout from '../views/layout/index.vue';
// import Articles from '../views/articles/index.vue';
// import AddArticle from '../views/articles/add.vue';
// import EditArticle from '../views/articles/edit.vue';
// import Image from '../views/image/index.vue';
// import Comment from '@/views/comment/index.vue';
// import Fans from '@/views/fans/index.vue';
// import Settings from '@/views/settings/index.vue';
// import Home from '../views/home/index.vue';
// import NotFound from '../views/notfound/index.vue';
// 上面的写法，会导致所有的组件全部打包在.js中，影响首屏加载
// 组件的引用改为函数的写法
// 路由懒加载：在访问不同的“页面"时，去加载本页面需要的.js，而不是在项目打开之初就全部加载
const Login = () => import('../views/login/index.vue');
const Layout = () => import('../views/layout/index.vue');
const Articles = () => import('../views/articles/index.vue');
const AddArticle = () => import('../views/articles/add.vue');
const EditArticle = () => import('../views/articles/edit.vue');
const Image = () => import('../views/image/index.vue');
const Comment = () => import('@/views/comment/index.vue');
const Fans = () => import('@/views/fans/index.vue');
const Settings = () => import('@/views/settings/index.vue');
const Home = () => import('../views/home/index.vue');
const NotFound = () => import('../views/notfound/index.vue');

Vue.use(VueRouter);

const routes = [
  // 一级路由
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    name: 'layout',
    component: Layout,
    children: [
      // 二级路由
      { path: '/articles', name: 'articles', component: Articles },
      { path: '/addArticle', name: 'addArticle', component: AddArticle },
      // 动态路由 编辑文章
      { path: '/editArticle/:id', name: 'editArticle', component: EditArticle },
      // 素材管理
      { path: '/image', name: 'image', component: Image },
      // path是空的表示展示默认组件
      { path: '', name: 'home', component: Home },
      // 评论管理
      { path: '/comment', name: 'comment', component: Comment },
      // 粉丝管理
      { path: '/fans', name: 'fans', component: Fans },
      // 个人设置
      { path: '/settings', name: 'settings', component: Settings }
    ]
  },
  { path: '*', component: NotFound }
];

const router = new VueRouter({
  routes
});

// 路由导航守卫
// 所有的路由页面跳转都会先进入该函数中
// to:要去哪里
// from:从哪里来
// next: 放行方法
//   -next()正确跳转，允许进入到to路由
//   -next(路由地址)不允许进入到to路由
router.beforeEach((to, from, next) => {
  console.log('路由导航守卫', to, from, next);
  if (to.path === '/') {
    // 要进入主页，先检查是否有登录信息，有则放行；没有则回去登录
    const userInfo = getUser();
    if (userInfo && userInfo.token) {
      next();
    } else {
      next('/login');
    }
  } else {
    // 如果不是去主页,直接放行
    next();
  }
});
export default router;
